﻿Option Explicit On
Option Strict On
Imports AuthorizeNet
Imports System.Globalization
Imports System.Data
Imports System.Data.SqlClient



Partial Class private_secure_members_payment_ConfirmOrder
    Inherits System.Web.UI.Page
    Dim conn As SqlConnection
    Dim com As SqlCommand
    Dim reader As SqlDataReader

    Dim connectionString As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString

    Dim u As MembershipUser
    Dim personId As Int32




    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        'First thing is to get the unit price for this entity
        'Next thing is to calculate the amounts for the labels below Session("SelectedEntityID") =
        If Session("SelectedEntityID") Is Nothing Then
            Response.Redirect("~/private/secure_members/payment/BuyCredit.aspx")
        ElseIf Session("BuyDT") Is Nothing Then
            Response.Redirect("~/private/secure_members/payment/BuyCredit.aspx")

        Else
            FillVirtualProductsSession()
            BindList()
            CalculatePrice()
        End If


        'carsdetailsDT=carddetailsTA.GetData(
        'carddetailsTA.Update(
        If Not Page.IsPostBack Then
            'txtCardNumber.Text = "4111111111111111"
            'txtCVV.Text = "0116"
            'ExpDateTxtBox.Text = "123"
            FillYearsExpiry()
            FillYearsValidy()
        End If
        BindSelectCardGrid()
        Session.Remove("JustInsertedCard")
    End Sub

    Sub BindSelectCardGrid()

        Dim activecardsTA As New LogginsLogDSTableAdapters.usp_CardDetailsSelectByEntityId_DDLTableAdapter()
        Dim activecardsDT As LogginsLogDS.usp_CardDetailsSelectByEntityId_DDLDataTable

        activecardsDT = activecardsTA.GetData(CType(Session("SelectedEntityID").ToString().Replace("""", ""), Integer?))
        'carddetailsDT = carddetailsTA.GetData(Nothing)
        Dim fcard = (From c In activecardsDT.AsEnumerable() Select c).FirstOrDefault()

        If Not fcard Is Nothing Then
            If Not Page.IsPostBack Then
                Dim carddetailsTA As New LogginsLogDSTableAdapters.usp_CardDetailsSelectTableAdapter()
                Dim carddetailsDT As LogginsLogDS.usp_CardDetailsSelectDataTable

                carddetailsDT = carddetailsTA.GetData(fcard.Id)

                Dim cards = (From q In carddetailsDT.AsEnumerable() Select q).FirstOrDefault()

                txtCardNumber.Text = cards.CardNumber
                txtCVV.Text = cards.CVV
                cboCardValidMM.SelectedValue = CStr(cards.ValidFromMonth)
                cboCardValidYY.SelectedValue = CStr(cards.ValidFromYear)
                cboCardExpiryMM.SelectedValue = CStr(cards.ExpireMonth)
                cboCardExpiryYY.SelectedValue = CStr(cards.ExpireYear)

                cboCCType.SelectedValue = CStr(cards.CardTypeId)
            End If
        Else
            'NewCardModalPopupExtender.Show()
        End If
        If Not Session("JustInsertedCard") Is Nothing Then
            Dim carddetailsTA As New LogginsLogDSTableAdapters.usp_CardDetailsSelectTableAdapter()
            Dim carddetailsDT As LogginsLogDS.usp_CardDetailsSelectDataTable

            carddetailsDT = carddetailsTA.GetData(CType(Session("JustInsertedCard"), Integer?))

            Dim cards = (From q In carddetailsDT.AsEnumerable() Select q).FirstOrDefault()

            txtCardNumber.Text = cards.CardNumber
            txtCVV.Text = cards.CVV
            cboCardValidMM.SelectedValue = CStr(cards.ValidFromMonth)
            cboCardValidYY.SelectedValue = CStr(cards.ValidFromYear)
            cboCardExpiryMM.SelectedValue = CStr(cards.ExpireMonth)
            cboCardExpiryYY.SelectedValue = CStr(cards.ExpireYear)

            cboCCType.SelectedValue = CStr(cards.CardTypeId)

        End If
        'Dim cards = From q In carddetailsDT.AsEnumerable() Where q.EntityId = CDbl(Session("SelectedEntityID").ToString()) Select q
        'GridView1.DataSource = activecardsDT
        'GridView1.DataBind()
        If Not Page.IsPostBack Then
            ddlSavedCreditCards.DataSource = activecardsDT
            ddlSavedCreditCards.DataTextField = "Details"
            ddlSavedCreditCards.DataValueField = "Id"
            ddlSavedCreditCards.DataBind()

        End If

    End Sub


    Sub FillYearsValidy()
        Dim year = CInt(Date.Now.Year) - 2004
        Dim yearsDT As DataTable = GetYearsTable()
        For index = 0 To 4
            yearsDT.Rows.Add(year + index)
        Next
        cboCardValidYY.DataSource = yearsDT
        cboCardValidYY.DataTextField = "Year"
        cboCardValidYY.DataValueField = "Year"
        cboCardValidYY.DataBind()
    End Sub


    Sub FillYearsExpiry()
        Dim year = CInt(Date.Now.Year) - 2000
        Dim yearsDT As DataTable = GetYearsTable()
        For index = 0 To 5
            yearsDT.Rows.Add(year + index)
        Next
        cboCardExpiryYY.DataSource = yearsDT
        cboCardExpiryYY.DataTextField = "Year"
        cboCardExpiryYY.DataValueField = "Year"
        cboCardExpiryYY.DataBind()
    End Sub
    Sub BindList()
        Dim table As DataTable = CType(Session("BuyDT"), DataTable)
        Dim uprice As Object
        Dim itemsbyentityTA As New LogginsLogDSTableAdapters.usp_ShowCreditsByEntityTableAdapter()
        Dim itemsbyentityDT As LogginsLogDS.usp_ShowCreditsByEntityDataTable
        itemsbyentityDT = itemsbyentityTA.GetData(CInt(Session("SelectedEntityID").ToString()), CType(uprice, Decimal?))
        Dim VirtualItems As DataTable = GetTable()
        For Each itemRow As LogginsLogDS.usp_ShowCreditsByEntityRow In itemsbyentityDT

            For Each dRow As DataRow In table.Rows
                If itemRow.ItemId = CInt(dRow("ItemId")) Then
                    VirtualItems.Rows.Add(itemRow.Name, itemRow.Units, itemRow.Price, itemRow.Price, itemRow.VAT_Amount, itemRow.Total)
                End If
            Next


        Next
        ListView1.DataSource = VirtualItems
        ListView1.DataBind()
    End Sub

    Function GetYearsTable() As DataTable
        ' Create new DataTable instance.
        Dim table As New DataTable
        ' Create four typed columns in the DataTable.
        table.Columns.Add("Year", GetType(Integer))

        Return table
    End Function


    Function GetTable() As DataTable
        ' Create new DataTable instance.
        Dim table As New DataTable
        ' Create four typed columns in the DataTable.
        table.Columns.Add("Name", GetType(String))
        table.Columns.Add("Units", GetType(String))
        table.Columns.Add("Price", GetType(String))
        table.Columns.Add("Sub Total", GetType(String))
        table.Columns.Add("VAT Amount", GetType(String))
        table.Columns.Add("Total", GetType(String))

        Return table
    End Function
    Sub CalculatePrice()
        Dim dec As Decimal
        Dim ProductsTA As New LogginsLogDSTableAdapters.usp_ShowCreditsByEntityTableAdapter()
        Dim ProductsDT As LogginsLogDS.usp_ShowCreditsByEntityDataTable
        If Not Session("SelectedEntityID") Is Nothing Then
            Dim x As Integer = CInt(Session("SelectedEntityID"))
            ProductsDT = ProductsTA.GetData(x, Convert.ToDecimal(dec))
            lblSubTotal.Text = CStr(0)
            lblFinalTotal.Text = CStr(0)
            lblVAT.Text = CStr(0)
            If Not Session("BuyDT") Is Nothing Then
                Dim table As DataTable = CType(Session("BuyDT"), DataTable)
                For Each dRow As DataRow In table.Rows
                    Dim price = (From p In ProductsDT.AsEnumerable() Where p.ItemId = CInt(dRow("ItemId")) Select p).FirstOrDefault()
                    lblFinalTotal.Text = CStr(Convert.ToDecimal(lblFinalTotal.Text) + Convert.ToDecimal(price.Total))
                    lblSubTotal.Text = CStr(Convert.ToDecimal(lblSubTotal.Text) + Convert.ToDecimal(price.Price))
                    lblVAT.Text = CStr(Convert.ToDecimal(lblVAT.Text) + Convert.ToDecimal(price.VAT_Amount))
                Next
            End If
        End If
    End Sub

    Protected Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click


        Dim responseID As String = ExecutePayment(CInt(lblFinalTotal.Text).ToString())
        AddNewCard(responseID)

    End Sub
    Function CheckDuplicates(EntityId As Integer, CardNumber As String) As Integer

        conn = New SqlConnection(connectionString)
        com = New SqlCommand()
        Dim parmOUT As New SqlParameter("@bExists", SqlDbType.SmallInt)
        parmOUT.Direction = ParameterDirection.Output

        com.Connection = conn

        com.CommandType = CommandType.StoredProcedure

        com.CommandText = "pay.usp_CardDetails_Exist"

        com.Parameters.Add("@EntityId", Data.SqlDbType.Int).Value = EntityId
        com.Parameters.Add("@CardNumber", Data.SqlDbType.NVarChar).Value = CardNumber
        com.Parameters.Add(parmOUT)

        conn.Open()
        com.ExecuteNonQuery()
        conn.Close()

        Return CInt(com.Parameters("@bExists").Value)
    End Function

    Sub AddNewCard(responseID As String)
        Dim y As Object
        u = Membership.GetUser(HttpContext.Current.User.Identity.Name)

        Dim getpersonid As New GetPersonIdFromUserId()

        personId = getpersonid.GetPersonId(CType(u.ProviderUserKey, Guid))
        Dim persondetailsTA As New LogginsLogDSTableAdapters.PersonTableAdapter()
        Dim persondetailsDT As LogginsLogDS.PersonDataTable
        persondetailsDT = persondetailsTA.GetData(CType(u.ProviderUserKey, Guid))
        Dim person = (From p In persondetailsDT.AsEnumerable() Select p).FirstOrDefault()

        Dim subStringl4d As String = Right(txtCardNumber.Text, 4)


        If CInt(lblFinalTotal.Text) <> 0 Then

            'If CheckCardNumber() AndAlso CheckExpDate() AndAlso CheckCVVNumber() Then
            If CheckCardNumber() AndAlso CheckExpDate() Then
                Dim payrequestTA As New LogginsLogDSTableAdapters.usp_PayRequestTableAdapter()
                Dim buycredits_startTA As New LogginsLogDSTableAdapters.SPTableAdapter()
                Dim usp_BuyCredits_CompleteTA As New LogginsLogDSTableAdapters.usp_BuyCredits_CompleteTableAdapter()
                Dim usp_BuyCredits_ErrorTA As New LogginsLogDSTableAdapters.SPTableAdapter()
                Dim carddetailsinsertTA As New LogginsLogDSTableAdapters.SPTableAdapter()

                If Not responseID = "error" Then
                    If Not Session("SelectedEntityID") Is Nothing Then


                        Dim table As DataTable = CType(Session("VirtualProductsDT"), DataTable)
                        For Each dRow As DataRow In table.Rows

                            If chkSaveCreditCard.Checked = True Then
                                Dim x As Integer
                                Dim selectedentity As Integer = CInt(Session("SelectedEntityID").ToString().Replace("""", ""))

                                Dim carddetailsaTA As New LogginsLogDSTableAdapters.usp_CardDetailsSelectTableAdapter()
                                Dim carddetailsaDT As LogginsLogDS.usp_CardDetailsSelectDataTable

                                carddetailsaDT = carddetailsaTA.GetData(Nothing)
                                Dim findduplicates = From q In carddetailsaDT.AsEnumerable() Where q.CardNumber = txtCardNumber.Text.Replace("""", "").Replace(" ", "") AndAlso q.EntityId = selectedentity Select q
                                Dim xx As String = findduplicates.ToList().Count.ToString()
                                'Dim findduplicates As Integer = CheckDuplicates(CInt(Session("SelectedEntityID").ToString().Replace("""", "").Replace(" ", "")), txtCardNumber.Text.Replace("""", ""))

                                If findduplicates.ToList().Count = 0 Then
                                    'If Not Session("JustInsertedCard") Is Nothing Then
                                    x = CInt(carddetailsinsertTA.usp_CardDetailsInsert(CInt(Session("SelectedEntityID")), person.FirstName, person.LastName, txtCardNumber.Text.Replace("""", "").Replace(" ", ""), subStringl4d, txtCVV.Text, CType(cboCCType.SelectedValue, Integer?), CType(cboCardExpiryMM.SelectedValue, Integer?), CType(cboCardExpiryYY.SelectedValue, Integer?), CType(cboCardValidMM.SelectedValue, Integer?), CType(cboCardValidYY.SelectedValue, Integer?), Date.Now, CType(1, Boolean?)))

                                    'Else

                                    'End If

                                Else
                                    Dim activecardsTA As New LogginsLogDSTableAdapters.usp_CardDetailsSelectByEntityId_DDLTableAdapter()
                                    Dim activecardsDT As LogginsLogDS.usp_CardDetailsSelectByEntityId_DDLDataTable

                                    activecardsDT = activecardsTA.GetData(selectedentity)
                                    Dim activecards = (From q In activecardsDT.AsEnumerable() Select q).FirstOrDefault()
                                    x = activecards.Id
                                End If


                                y = buycredits_startTA.usp_BuyCredits_Start(personId, CInt(Session("SelectedEntityID")), CType(cboCCType.SelectedValue, Byte?), 1, 1, CInt(dRow("ItemId")), CType(ddCurrency.SelectedValue, Integer?), CType(0.0, Decimal?), "Pending", CType(x, Integer?))
                            Else
                                'TODO: if check box is unchecked 
                            End If


                        Next
                    End If

                    usp_BuyCredits_CompleteTA.GetData(CInt(Session("SelectedEntityID")), (CType(y, Integer?)), responseID)
                    '
                    Dim strMailFrom As String = ConfigurationManager.AppSettings("smtpmailfrom").ToString()
                    Dim strMailTo As String = ConfigurationManager.AppSettings("accountapprovalemail").ToString()
                    Dim sendemail As New SendEmailViaGoogle()

                    Dim strMessage As String = "Thank you for your payment. Your transaction has been successfully processed and completed." + "Your invoice ID is " + responseID
                    Dim strSubject As String = "Invoice"


                    Try

                        sendemail.SendEmail(strMailFrom, strMailTo, strSubject, strMessage)
                        Session("BuyDT") = Nothing
                        Response.Redirect("~/private/secure_members/payment/ThankYou.aspx")
                    Catch ex As Exception
                        Throw ex
                    End Try

                Else
                    usp_BuyCredits_ErrorTA.usp_BuyCredits_Error(CInt(Session("SelectedEntityID")), (CType(y, Integer?)), responseID)
                End If
            End If
        Else
            MsgLbl.Text = ("Close this window and select one or more item from the list first.")
        End If

    End Sub


    Private Function OpenGateway() As IGateway
        Dim login = ConfigurationManager.AppSettings("ApiLogin")
        Dim transactionKey = ConfigurationManager.AppSettings("TransactionKey")

        Dim gate = New Gateway(login, transactionKey, True)
        Return gate
    End Function

    Private Function ExecutePayment(ByVal credits As String) As String
        Dim gate = OpenGateway()
        Dim apiRequest = CheckoutFormReaders.BuildAuthAndCaptureFromPost()

        Try
            Dim price As [String] = credits
            Dim cardNumber As [String] = txtCardNumber.Text
            Dim expDate As [String] = "123" 'This is just for developemnt purposes
            'Dim expDate As [String] = cboCardExpiryMM.SelectedValue.ToString() + cboCardExpiryYY.DataValueField.ToString()
            Dim ccv As [String] = txtCVV.Text

            apiRequest.Queue(ApiFields.Amount, price)
            apiRequest.Queue(ApiFields.CreditCardNumber, cardNumber)
            apiRequest.Queue(ApiFields.CreditCardExpiration, expDate)
            apiRequest.Queue(ApiFields.CreditCardCode, ccv)
        Catch
            Return "error"
        End Try

        Dim response = gate.Send(apiRequest)

        If response.Approved Then

            Dim AuthCode As String = response.AuthorizationCode
            Dim Approved As Boolean = response.Approved
            Dim TransactionID As String = response.TransactionID
            Dim OrderMessage As String = String.Format("Thank you! Order approved: {0}", response.AuthorizationCode)

            MsgLbl.Text = "Response message is: " & Convert.ToString(response.Message) & "</br>" & "Response code is: " & Convert.ToString(response.ResponseCode) & "</br>" & "TransactionID is: " & Convert.ToString(response.TransactionID)

            Return TransactionID
        Else
            Dim OrderMessage As String = response.Message
            MsgLbl.Text = "Response message is: " & Convert.ToString(response.Message) & "</br>" & "Response code is: " & Convert.ToString(response.ResponseCode)
            Return "error"
        End If
    End Function
    'Function FormatDecimalToCurrency(ByVal Value As Decimal) As String
    '    Dim nfi As NumberFormatInfo = New CultureInfo("en-AU", False).NumberFormat
    '    Dim num As Decimal = Decimal.Parse(CStr(Value))
    '    Return num.ToString("C", nfi)
    'End Function

    'Function ConvertStringToDecimal(ByVal Value As String) As String
    '    Dim cardnum As String = ""
    '    For Each chr As Char In Value
    '        If Char.IsNumber(chr) OrElse chr = "." Then
    '            cardnum += chr
    '        End If
    '    Next
    '    Return cardnum
    'End Function
    Function CheckCardNumber() As Boolean

        ' Validation not working
        'Return True

        Dim validation As Boolean
        Dim cardnum = txtCardNumber.Text.Replace("_", "").Replace("""", "")
        'txtCardType1.Text = cardnum
        'cboCCType
        Dim selected = cboCCType.SelectedValue.ToString()
        If cardnum.Length > 0 Then
            If cardnum.Length > 4 Then
                Dim trimedtext As String = cardnum.Replace(" ", "")
                Dim trimedtext1 As String = trimedtext.Substring(0, 1)
                Dim trimedtext2 As String = trimedtext.Substring(0, 2)
                Dim trimedtext3 As String = trimedtext.Substring(0, 3)
                Dim trimedtext4 As String = trimedtext.Substring(0, 4)
                If selected = "1" Then
                    If CDbl(trimedtext1) = 4 Then
                        If trimedtext.Length = 13 OrElse trimedtext.Length = 16 Then
                            MsgLbl.Text = ("Visa is ok")

                            validation = True
                        Else
                            MsgLbl.Text = ("Visa is NOT ok")
                            validation = False
                        End If
                    Else
                        MsgLbl.Text = ("Visa number is NOT ok")
                    End If


                End If
                If selected = "2" Then
                    If CDbl(trimedtext2) = 36 OrElse CDbl(trimedtext2) = 51 OrElse CDbl(trimedtext2) = 52 OrElse CDbl(trimedtext2) = 53 OrElse CDbl(trimedtext2) = 54 OrElse CDbl(trimedtext2) = 55 Then
                        If trimedtext.Length = 14 OrElse trimedtext.Length = 16 Then
                            MsgLbl.Text = ("Mastercard is ok")
                            validation = True
                        Else
                            MsgLbl.Text = ("Mastercard is NOT ok")
                            validation = False
                        End If
                    Else
                        MsgLbl.Text = ("Mastercard number is NOT ok")
                    End If

                End If

            End If
        Else
            MsgLbl.Text = "Please enter valid cart number it must be more then 4 digits."
            validation = False
        End If
        Return validation
    End Function

    Function CheckExpDate() As Boolean
        Dim validation As Boolean
        If cboCardExpiryMM.SelectedItem IsNot Nothing AndAlso cboCardExpiryYY.SelectedItem IsNot Nothing Then
            Dim selectedmonth = cboCardExpiryMM.SelectedItem.ToString()
            Dim selectedyear = cboCardExpiryYY.SelectedItem.ToString()

            Dim currentmonth = Date.Today.Month
            Dim currentyear = Date.Today.Year

            If (currentyear - 2000).ToString() = selectedyear Then
                If currentmonth > CInt(selectedmonth) Then
                    MsgLbl.Text = ("Cart expired")
                    validation = False
                Else
                    validation = True
                End If
            ElseIf Not (currentyear - 2000).ToString() > selectedyear Then
                validation = True
            Else
                MsgLbl.Text = ("Cart expired")
                validation = False
            End If

        Else

        End If

        Return validation

    End Function

    Function CheckCVVNumber() As Boolean
        Dim validation As Boolean
        Dim number As Integer
        Dim CVVnum As Boolean = Int32.TryParse(txtCVV.Text.Replace("_", "").Replace(" ", ""), number)
        If CVVnum Then
            If txtCVV.Text.Replace(" ", "").Length = 4 Then

                If CVVnum Then
                    MsgLbl.Text = ("CVV has three numbers")
                    validation = True
                End If
            Else
                MsgLbl.Text = ("CVV must not be longer then three numbers")
                validation = False
            End If
        Else
            MsgLbl.Text = ("CVV has to be number")
            validation = False
        End If
        Return validation
    End Function




    Protected Sub ObjectDataSource3_Selecting(sender As Object, e As ObjectDataSourceSelectingEventArgs) Handles ObjectDataSource3.Selecting
        e.InputParameters("Id") = Nothing

    End Sub

    Protected Sub ODSCurrency_Selecting(sender As Object, e As ObjectDataSourceSelectingEventArgs) Handles ODSCurrency.Selecting
        e.InputParameters("Id") = Nothing

    End Sub

    Protected Sub ButtonCancel_Click(sender As Object, e As EventArgs) Handles ButtonCancel.Click
        Response.Redirect("~/private/secure_members/payment/BuyCredit.aspx")

    End Sub

    Sub FillVirtualProductsSession()
        Dim dec As Decimal
        Dim ProductsTA As New LogginsLogDSTableAdapters.usp_ShowCreditsByEntityTableAdapter()
        Dim ProductsDT As LogginsLogDS.usp_ShowCreditsByEntityDataTable
        Dim VirtualProductsDT As DataTable = GetVirtualTable()
        If Not Session("SelectedEntityID") Is Nothing Then
            Dim x As Integer = CInt(Session("SelectedEntityID"))
            ProductsDT = ProductsTA.GetData(x, CType(dec, Decimal?))

            If Not Session("BuyDT") Is Nothing Then
            End If

            Dim table As DataTable = CType(Session("BuyDT"), DataTable)
            For Each dRow As DataRow In table.Rows
                For Each ProductsRow As LogginsLogDS.usp_ShowCreditsByEntityRow In ProductsDT
                    If ProductsRow.ItemId = CDbl(dRow("ItemId").ToString()) Then
                        VirtualProductsDT.Rows.Add(ProductsRow.ItemId, ProductsRow.Name, ProductsRow.Units, ProductsRow.Price)

                    End If

                    'Dim resultbyitmid = (From p In ProductsDT.AsEnumerable() Where p.ItemId =  Select p).FirstOrDefault()
                Next
            Next

            Session("VirtualProductsDT") = VirtualProductsDT

        End If
    End Sub

    Function GetVirtualTable() As DataTable
        ' Create new DataTable instance.Where p.ItemId = dRow("ItemId").ToString()
        Dim table As New DataTable
        ' Create four typed columns in the DataTable.
        table.Columns.Add("ItemId", GetType(Integer))
        table.Columns.Add("Name", GetType(String))
        table.Columns.Add("Units", GetType(String))
        table.Columns.Add("Price", GetType(String))
        Return table
    End Function


 



    Protected Sub cboCCType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCCType.SelectedIndexChanged
        If Not CInt(cboCCType.SelectedValue) <> 3 Then
            MultiView1.ActiveViewIndex = 0
        Else
            MultiView1.ActiveViewIndex = 1
        End If

    End Sub

    Protected Sub cboCCType_DataBound(sender As Object, e As EventArgs) Handles cboCCType.DataBound
        If Not CInt(cboCCType.SelectedValue) <> 3 Then
            MultiView1.ActiveViewIndex = 0
            If CDbl(cboCCType.SelectedValue) = 1 Then
                MaskedEditExtender1.Mask = "9999"
            ElseIf CDbl(cboCCType.SelectedValue) = 2 Then
                MaskedEditExtender1.Mask = "999"
            End If

        Else
            MultiView1.ActiveViewIndex = 1
        End If

    End Sub


    'Protected Sub GridView1_DataBound(sender As Object, e As EventArgs) Handles GridView1.DataBound
    '    Dim count = GridView1.Rows.Count
    '    If count <> 0 Then
    '        Panel3.Visible = True
    '    Else
    '        Panel3.Visible = False
    '    End If
    'End Sub
    'Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand
    '    If e.CommandName = "CustomSelect" Then
    '        Try
    '            carddetailsDT = carddetailsTA.GetData(Nothing)

    '            Dim cards = (From q In carddetailsDT.AsEnumerable() Where q.Id = Convert.ToInt32(e.CommandArgument) Select q).FirstOrDefault()


    '            txtCardNumber.Text = cards.CardNumber
    '            txtCVV.Text = cards.CVV
    '            cboCardValidMM.SelectedValue = CStr(cards.ValidFromMonth)
    '            cboCardValidYY.SelectedValue = CStr(cards.ValidFromYear)
    '            cboCardExpiryMM.SelectedValue = CStr(cards.ExpireMonth)
    '            cboCardExpiryYY.SelectedValue = CStr(cards.ExpireYear)
    '            cboCCType.SelectedValue = CStr(cards.CardTypeId)
    '            'ddCurrency.SelectedValue = CStr(cards.)


    '        Catch ex As Exception
    '            Throw ex
    '        End Try
    '    ElseIf e.CommandName = "AddCard" Then
    '        NewCardModalPopupExtender.Show()
    '    End If

    'End Sub

    Protected Sub ddlSavedCreditCards_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlSavedCreditCards.SelectedIndexChanged
        Try
            Dim carddetailsTA As New LogginsLogDSTableAdapters.usp_CardDetailsSelectTableAdapter()
            Dim carddetailsDT As LogginsLogDS.usp_CardDetailsSelectDataTable

            carddetailsDT = carddetailsTA.GetData(Nothing)

            Dim cards = (From q In carddetailsDT.AsEnumerable() Where q.Id = Convert.ToInt32(ddlSavedCreditCards.SelectedValue) Select q).FirstOrDefault()


            txtCardNumber.Text = cards.CardNumber
            txtCVV.Text = cards.CVV
            cboCardValidMM.SelectedValue = CStr(cards.ValidFromMonth)
            cboCardValidYY.SelectedValue = CStr(cards.ValidFromYear)
            cboCardExpiryMM.SelectedValue = CStr(cards.ExpireMonth)
            cboCardExpiryYY.SelectedValue = CStr(cards.ExpireYear)
            cboCCType.SelectedValue = CStr(cards.CardTypeId)
            'ddCurrency.SelectedValue = CStr(cards.)


        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Protected Sub ddlSavedCreditCards_DataBound(sender As Object, e As EventArgs) Handles ddlSavedCreditCards.DataBound
        Dim count = ddlSavedCreditCards.Items.Count
        If count <> 0 Then
            Panel3.Visible = True
            ddlSavedCreditCards.Visible = True
            Button9.Visible = True
            MsgLbl.Text = "Please select a payment card from the list"
        Else
            Panel3.Visible = False
            ddlSavedCreditCards.Visible = False
            Button9.Visible = False

            MsgLbl.Text = "You have no saved payment cards – please add a card"
        End If
    End Sub

    Protected Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        NewCardModalPopupExtender.Show()
    End Sub

    Protected Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        Response.Redirect("~/private/secure_members/manage/MyCardDetails.aspx")

    End Sub
End Class
